<?php

namespace App\Http\Controllers\Pc;

use App\Lib\CreateStaticNumber;
use App\Models\CardType;
use App\Models\UserStore;
use App\Modules\MemberCard\Repositores\MemberCardFlowRepository;
use App\Modules\MemberCard\Repositores\MemberCardRepository;
use App\Modules\System\Repositories\AmountFlowRepository;
use Illuminate\Http\Request;

use App\Models\Admin\Admin;
use App\Models\Vipcard;
use App\Models\Store;
use App\Models\MemberCard;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use DB;

class VipcardController extends Controller
{
    public function index(Request $request){
        $store_id = decrypt($request->route('store_id'));
        $user_id = session('user_id');

        //判断有无权限
        if(!UserStore::where('uid',$user_id)->where('rid',1)->where('sid',$store_id)->first()){
            return '404 not found';
        }
        //获取店铺列表
        $store_list = UserStore::where('uid',$user_id)->where('rid',1)->get();

        //获取转移历史

        $return_data = [];
        $store_name = Store::where('id',$store_id)->first()['name'];

        $user_vip = MemberCard::where('store_id',$store_id)->where('source',3)->get();
         foreach ($user_vip as $key => $value) {
             $return_data[] = [
                 'id'=>$value->id,
                 'name'=>$value->name,
                 'phone'=>$value->phone,
                 'status'=>$value->user_id==0?0:1,
                 'created_at'=>$value->created_at,
             ];
         }
        return view('pc.index')
            ->with('history',$user_vip)
            ->with('store_name',$store_name)
            ->with('store_list',$store_list)
            ->with('store_id',encrypt($store_id))
            ;
    }


    public function excelUpload(Request $request){

        if($request->file('excel')->getClientOriginalExtension()!="xlsx"){
            return [
                'status'=> 0,
                'msg'=>'请上传正确格式的文件',

            ];
        }
        $store_id = decrypt($request->input('store_id'));
        $fileName = md5(time().rand(1000,9999));
        $card_front_suffix  = $request->file('excel')->getClientOriginalExtension();

        $card_front_path = $request->file('excel')->move('uploads/excel',$fileName.'.'.$card_front_suffix);


        return [
            'status'=> 1,
            'msg'=>'',
            'result'=> [
                'file_name'=>encrypt($card_front_path->getPathname()),
                'store_id'=>encrypt($store_id)
                ]

        ];

    }

    public function excelPut(Request $request){
        echo "
        
        <link href='https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css' rel='stylesheet'>
        <style>
            .history,.uploading{
                position: fixed;
                width: 50%;
                height: 80vh;
                left: 50%;
                margin-left: -25%;
                background: #fff;
                top: 50vh;
                margin-top: -40vh;
                border: none;
                /*display: none;*/
            }
            .history-top,.uploading-top{
                width: 100%;
                overflow: hidden;
            }
            .history-top-exit,.uploading-top-exit{
                float: right;
                padding: 0 10px 0 0;
                transition: all .5s;
                color:#929192;
            }
            .history-top-exit i,.uploading-top-exit i{transition: all .3s;cursor: pointer;}
            .history-top-exit i:hover,.uploading-top-exit i:hover{
                transform:rotate(45deg);
            }
            .history-list,.uploading-list{
                padding: 20px;
                margin: 0;
                list-style: none;
                width: 100%;

            }
            .history-list-item,.uploading-list-item{
                display: flex;
                text-align: center;
                justify-content: center;
                font-size: 14px;
                color:#929192;
                margin: 5px 0;
            }
            .history-list-item-id,.uploading-list-item-id{
                flex: 1;
            }
            .history-list-item-name,.uploading-list-item-name{
                flex: 2;
            }
            .history-list-item-phone,.uploading-list-item-phone{
                flex: 4;
            }
            .history-list-item-time,.uploading-list-item-time{
                flex: 4;
            }
            .history-list-item-status,.uploading-list-item-status{
                flex: 3;
            }
            .history-bottom,.uploading-bottom{
                position: absolute;
                bottom: 0;
                height: 20px;
                width: 100%;
            }
            .uploading-list-item-error i{
                color:#d9534f;
            }
            .fa-check-circle{
                color:#5cb85c;
            }
            </style>";


        $fileName =decrypt($request->route('fileName'));//解密文件名
        $store_id =decrypt($request->route('store_id'));//解密店铺id
        $filePath = 'public/'.$fileName;
        $user_id = session('user_id');
        Excel::load($filePath, function($reader) use ($store_id,$user_id){


            DB::beginTransaction();//开启事务
            $line = 2;//初始化行数
            $data = $reader->all();
            $user_vipcard = MemberCard::where('store_id',$store_id)->where('user_id',0)->where('source',3)->delete();


            try{
                foreach ($data as $key => $value) {
                    echo str_repeat ( " " , 1024*8 ) ;//占位 缓存

                    if(!isset($value['姓名'])){
                        echo "<script>alert('请上传正确格式的文件')</script>";
                        DB::rollBack();
                        return  false;
                    }
                    //判断是否结束
                    if($value['姓名']=='[结束]'){
                        echo '<li class="uploading-list-item">
                                <div class="uploading-list-item-id">转移成功 共转移了'.($line-2).'条数据</div>
                            </li>'  ;
                        DB::commit();
                        return true;
                    }
                    if($value['姓名']==null&&$value['会员卡名']==null&&$value['手机号']==null&&$value['性别']==null&&$value['剩余金额']==null){//所有行都为空也是结束
                        echo '<li class="uploading-list-item">
                                <div class="uploading-list-item-id">转移成功 共转移了'.($line-2).'条数据</div>
                            </li>'  ;

                        DB::commit();
                        return true;
                    }
                    // if($line==3){
                    //     dd($value['手机号']==null);
                    // }

                    //根据名字获取会员卡id
                    $vipcard_name = $value['会员卡名'];

                    if($vipcard_name==null){
                        $this->echoItem(0,$line,'','','空','');
                        echo "<script>alert('第".$line."行数据错误 请填写会员卡名')</script>";
                        DB::rollBack();
                        return  false;
                    }


                    // $vipcard_line = $value['序号'];

                    $user_name = $value['姓名'];


                    if($user_name==null){
                        $this->echoItem(0,$line,'空','',$vipcard_name,'');
                        echo "<script>alert('第".$line."行数据错误 请填写会员名')</script>";
                        DB::rollBack();
                        return  false;
                    }

                    $user_phone = $value['手机号'];

                    if($user_phone==null){
                        $this->echoItem(0,$line,$user_name,'空',$vipcard_name,'');
                        echo "<script>alert('第".$line."行数据错误 请填写会员手机号')</script>";
                        DB::rollBack();
                        return  false;
                    }


                    $user_sex = $value['性别']=='男'?1:2;



                    //判断余额是否正确
                    if($value['剩余金额']==null){
                        $balance_text = round($value['剩余金额'],2).'元';
                        $this->echoItem(0,$line,$user_name,$user_phone,$vipcard_name,$balance_text);
                        echo "<script>alert('第".$line."行数据错误 请填写用户余额')</script>";
                        DB::rollBack();
                        return  false;
                    }else{
                        $balance = $value['剩余金额'];
                        $count = 0;
                        $balance_text = round($value['剩余金额'],2).'元';
                    }

                    //判断店内已添加该会员卡
                    //
                    $vipcard = CardType::where('name',$vipcard_name)->where('store_id',$store_id)->first();
                    if(!$vipcard){
                        $this->echoItem(0,$line,$user_name,$user_phone,$vipcard_name,'');
                        echo "<script>alert('第".$line."行数据错误 店长还没有添加名为".$vipcard_name."的会员卡')</script>";
                        DB::rollBack();
                        return  false;
                    }

                    //判断手机号码格式是否正确

                    if(!preg_match("/^1[345678]{1}\d{9}$/",$user_phone)){
                        $this->echoItem(0,$line,$user_name,$user_phone,$vipcard_name,$balance_text);
                        echo "<script>alert('第".$line."行数据错误 手机号码格式错误')</script>";
                        DB::rollBack();
                        return  false;
                    }
                    $num = CreateStaticNumber::makeNo('card');

                    $category = 2;

                    $member_card_repository = new MemberCardRepository();
                    $member_card = $member_card_repository->createMemberCard($store_id,$vipcard['id'],$user_name,$user_phone,$user_sex,$category,$count,$balance,1,$user_id,0,$num,3);
                    $vipcard_flow_repository = new MemberCardFlowRepository();
                    $vipcard_flow = $vipcard_flow_repository->transfer($member_card->id,$store_id,$vipcard['caregory'],$user_id,$count,$balance);
                    $this->echoItem(1,$line,$user_name,$user_phone,$vipcard_name,$balance_text);

                    $line++;
                    ob_flush ( ) ;
                    flush ( ) ;
                    usleep (100000);
                }
                DB::commit();
                return true;
            }catch(Exception $e){
                DB::rollBack();
                echo "未知错误";
                return false;
            }

        });


    }

    protected function echoItem($type,$line,$user_name,$user_phone,$vipcard_name,$balance){
        // dd($line);
        if($type==1){
            echo '<li class="uploading-list-item">
                    <div class="uploading-list-item-id">'.$line.'</div>
                    <div class="uploading-list-item-name">'.$user_name .'</div>
                    <div class="uploading-list-item-phone">'.$user_phone.'</div>
                    <div class="uploading-list-item-time">'.$vipcard_name.'</div>
                    <div class="uploading-list-item-time">'.$balance.'</div>
                    <div class="uploading-list-item-status"><i class="fa fa-check-circle"></i></div>
                </li>'  ;
        }else{
            echo '<li class="uploading-list-item  uploading-list-item-error">
                <div class="uploading-list-item-id">'.$line.'</div>
                <div class="uploading-list-item-name">'.$user_name .'</div>
                <div class="uploading-list-item-phone">'.$user_phone.'</div>
                <div class="uploading-list-item-time">'.$vipcard_name.'</div>
                    <div class="uploading-list-item-time">'.$balance.'</div>
                <div class="uploading-list-item-status"><i class="fa fa-close"></i></div>
            </li>'  ;
        }

    }
}
